import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';
import { Button, Drawer, Table, message, Typography } from 'antd';
import { getAuthAxios } from '../lib/authAxios.js';

const copyText = text => {
  if (window.navigator && window.navigator.clipboard && window.isSecureContext) {
    window.navigator.clipboard
      .writeText(text)
      .then(() => {
        message.success('已复制工单编号');
      })
      .catch(() => {
        fallbackCopyTextToClipboard(text);
      });
  } else {
    fallbackCopyTextToClipboard(text);
  }
};

function fallbackCopyTextToClipboard(text) {
  const textArea = document.createElement('textarea');
  textArea.value = text;
  textArea.style.position = 'fixed';
  textArea.style.top = '-1000px';
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();
  try {
    document.execCommand('copy');
    message.success('已复制工单编号');
  } catch (err) {
    message.error('复制失败');
  }
  document.body.removeChild(textArea);
}

const columns = [
  {
    title: '工单编号',
    dataIndex: 'workOrderNo',
    key: 'workOrderNo',
    width: 120,
    render: text => (
      <Typography.Link style={{ color: '#1677ff' }} onClick={() => copyText(text)}>
        {text}
      </Typography.Link>
    )
  },
  {
    title: '预警类型',
    dataIndex: 'warningType',
    key: 'warningType',
    width: 120
  },
  {
    title: '时限',
    dataIndex: 'timeLimit',
    key: 'timeLimit',
    width: 80,
    render: text => {
      const hours = Number(text);
      if (isNaN(hours)) return text;
      
      const days = Math.floor(hours / 24);
      const remainingHours = hours % 24;
      
      let displayText = '';
      if (days > 0) {
        displayText += `${days}天`;
      }
      if (remainingHours > 0 || days === 0) {
        displayText += `${remainingHours}小时`;
      }
      
      return displayText;
    }
  },
  {
    title: '环节名称',
    dataIndex: 'nodeName',
    key: 'nodeName',
    width: 140
  },
  {
    title: '供电单位',
    dataIndex: 'supplyUnit',
    key: 'supplyUnit',
    width: 140
  }
];

// mock请求接口
const fetchTableData = async (tableType, page, pageSize) => {
  await new Promise(res => setTimeout(res, 300));
  if (tableType === 'table') {
    const total = 120;
    const data = Array.from({ length: total }, (_, i) => ({
      workOrderNo: `A${String(i + 1).padStart(3, '0')}`,
      warningType: `类型${(i % 5) + 1}`,
      timeLimit: `${24 + (i % 3) * 12}h`,
      nodeName: `环节${(i % 8) + 1}`,
      supplyUnit: `单位${(i % 4) + 1}`
    }));
    return {
      data: data.slice((page - 1) * pageSize, page * pageSize),
      total
    };
  }
};

const WarnTableDrawer = () => {
  const myAxios = getAuthAxios();
  const [open, setOpen] = useState(false);
  const [tablePage, setTablePage] = useState(1);
  const [tableData, setTableData] = useState([]);
  const [mockData, setMockData] = useState([]);
  const [dataSource, setDataSource] = useState([]);
  const [total, setTotal] = useState(0);
  const [pageSize, setPageSize] = useState(20);

  // 加载mock数据
  React.useEffect(() => {
    if (!tableData) {
      fetchTableData('table', 1, 120).then(res => {
        setMockData(res.data);
      });
    }
    // 分页处理
    const dataArr = Array.isArray(tableData) ? tableData : mockData;
    setDataSource(dataArr.slice((tablePage - 1) * pageSize, tablePage * pageSize));
    setTotal(dataArr.length);
    const current = tablePage;
  }, [tableData]);
  React.useEffect(() => {
    open && getWarinTableData();
    // function onGlobalVarChange(e) {
    //   if (window.getMyGlobalVar('warnTableData')) {
    //     setTableData(window.getMyGlobalVar('warnTableData'))
    //   }
    //   setTableData(window.getMyGlobalVar('warnTableData'))
    // }
    // window.addEventListener("MY_GLOBAL_VAR_CHANGE", onGlobalVarChange)
    // return () => window.removeEventListener("MY_GLOBAL_VAR_CHANGE", onGlobalVarChange)
  }, [open]);

  const getWarinTableData = () => {
    myAxios
      .post('http://10.158.212.196:34002/yxjc/api/yxjc/v1/yxjcAllertMsg/list ', { orgName: window.getMyGlobalVar('orgName') })
      .then(response => {
        if (response.data) {
          setTableData(response.data.data.list);
        }
        // console.log('warntabledata:', response.data);
      })
      .catch(error => {
        console.error(error);
      });
  };

  return (
    <>
      {!open && (
        <Button type='primary' style={{ position: 'fixed', right: 50, top: 150, zIndex: 99999 }} onClick={() => setOpen(true)}>
          预警列表
        </Button>
      )}
      <Drawer title='预警信息' placement='right' width={500} onClose={() => setOpen(false)} open={open} mask={false} style={{ zIndex: 99999 }}>
        <div style={{ marginBottom: 24 }}>
          <h3>预警信息列表</h3>
          <Table
            columns={columns}
            dataSource={dataSource}
            pagination={{
              current: tablePage,
              pageSize: pageSize,
              total: total,
              onChange: setTablePage,
              showSizeChanger: false
            }}
            rowKey='workOrderNo'
            size='small'
          />
        </div>
      </Drawer>
    </>
  );
};
const initWarnTable = () => {
  if (document.getElementById('warn-table-drawer')) {
    document.getElementById('warn-table-drawer').remove();
    return;
  }
  if (window.getMyGlobalVar && window.getMyGlobalVar('activeTabName') !== '全部工单') return;
  const container = document.createElement('div');
  container.id = 'warn-table-drawer';
  document.body.appendChild(container);
  const root = ReactDOM.createRoot(container);
  root.render(<WarnTableDrawer />);
};
initWarnTable();
